<template>
  <div id="app">
    <h1>家校共创系统</h1>
    <nav v-if="isLoggedIn">
      <router-link to="/student" v-if="userType === '2'">学生考勤</router-link> |
      <router-link to="/teacher" v-if="userType === '1'">教师管理</router-link> |
      <router-link to="/parent" v-if="userType === '3'">家长查看</router-link>
    </nav>
    <router-view />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';

export default {
  name: 'App',
  setup() {
    const router = useRouter();
    const userType = ref(null);
    const isLoggedIn = ref(false);

    // 获取用户类型
    const getUserType = async () => {
      try {
        const response = await fetch('/user/profile', {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        const result = await response.json();
        if (result.code === 1 && result.data) {
          userType.value = result.data.usertype;
          isLoggedIn.value = true;
        } else {
          // 如果未登录，跳转到登录页
          router.push('/login');
        }
      } catch (err) {
        console.error('获取用户信息失败:', err);
        // 如果出错，也跳转到登录页
        router.push('/login');
      }
    };

    onMounted(() => {
      // 只有在非登录/注册页面才检查用户状态
      const publicRoutes = ['/login', '/register'];
      if (!publicRoutes.includes(router.currentRoute.value.path)) {
        getUserType();
      }
    });

    return {
      userType,
      isLoggedIn
    };
  }
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

nav {
  padding: 30px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
}

nav a.router-link-exact-active {
  color: #42b983;
}
</style>